#include "stdafx.h"
#include "condition.h"
#include "econ.h"

Condition::~Condition() 
{
	delete this->e;
}

Retour Condition::evaluer(map<string, Var_T> *loc, map<string, Var_T> *glob)
{
	Retour ret;

	if (this->type == BRANCH_ELSE)
	{
		ret.code = RET_BRANCH_TAKEN;
	}
	else
	{
		if(e->evaluer(loc, glob).getBool()) {
			ret.code = RET_BRANCH_TAKEN;
		} else {
			ret.code = RET_BRANCH_IGNORED;
		}
	}

	return ret;
}

Instruction* conditionner(list<token> src)
{
	Condition *cond = new Condition();

	if (src.front().tok == "else")
	{
		if (src.size() != 1) {
			die("Error: Unexpected token after 'else' statement.");
		} else {
			cond->type = BRANCH_ELSE;
			cond->code = CODE_ELSE;
		}
	}
	else
	{
		if (src.front().tok == "if") {
			cond->type = BRANCH_IF;
			cond->code = CODE_IF;
		} else if(src.front().tok == "elif") {
			cond->type = BRANCH_ELIF;
			cond->code = CODE_ELIF;
		}

		src.pop_front();

		if (src.front().tok != "(")
			die("Error: Expected opening parenthesis after 'if/elif' keyword.");

		if (src.back().tok != ")")
			die("Error: Expected closing parenthesis after 'if/elif' statement.");

		src.pop_front();
		src.pop_back();

		if (validerEcon(src))
		{
			Econ *e = new Econ();
			e->construire(e->convertir(e->separer(src)));
			cond->e = e;
		}
		else
		{
			die("Error: Invalid conditional expression.");
		}
	}

	return cond;
}
